package cn.djb.day25;

/**
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
 */
class Solution {

    /**
     * 设置边界
     * @param matrix
     * @return
     */
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0) return new int[0];
        int[] res = new int[matrix.length * matrix[0].length];
        int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1, x = 0;

        while (true) {
            for (int i = l; i <= r; i++) {
                res[x++] = matrix[t][i];
            }
            if (++t > b) break;
            for (int i = t; i <= b; i++) {
                res[x++] = matrix[r][i];
            }
            if (--r < l) break;
            for (int i = r; i >= l ; i--) {
                res[x++] = matrix[i][b];
            }
            if (--b < t) break;
            for (int i = b; i >= t ; i--) {
                res[x++] = matrix[l][i];
            }
            if (++l > r) break;
        }
        return res;

    }
}